<!--#INCLUDE FILE="..\System\Include\incAll.asp"-->
<!--#INCLUDE FILE="..\System\Include\incEvents.asp"-->
<!--#INCLUDE FILE="..\System\Include\incAuthorization.asp"-->
<!--#INCLUDE FILE="..\System\Include\incAuthentication.asp"-->
<!--#INCLUDE FILE="..\System\Include\incBanner.asp"-->
<!--#INCLUDE FILE="..\System\Include\incForm.asp"-->
<%
':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
':::
':::  (c) 2001-2004 ExecuTRACK Software AG
':::
':::  Filename:   {PAGE_NAME}.asp
':::  Author:     {AUTHOR_NAME}
':::  Created:    {CREATION_DATE}
':::  Version:    ASP 3.0
':::
':::  Purpose:
':::    Form to edit a {TABLE_NAME}.
':::
':::  Parameters:
':::    {PAGE_KEY} - Page key for this form.
':::
':::  Revision History:
':::    Author dd-mmm-yyyy Purpose
':::
':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
':::  Constant Declarations
':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

  '::: Object name for retrieving resources and authorization.
  Const mcstrObjectName = "{PAGE_NAME}.asp"

  '::: Stored procedures that retrieve and save data for this page
  Const mcstrSP_Get  = "pfrm{PAGE_NAME}_Get"
  Const mcstrSP_Save = "pfrm{PAGE_NAME}_Save"

':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
':::  Variable Declarations
':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

                          '::: -----  Page Elements  -----
  Dim mconConnection      '::: Database connection.
  Dim mintUserID          '::: Authenticated user ID.
  Dim mobjContext         '::: Object context.
  Dim mobjResourceDict    '::: ResourceDict object for fetching language-
                          '::: dependant text and other resources.
  Dim mobjPageStatus      '::: PageStatus object to hold information about
                          '::: the status of the page, like HTTP status
                          '::: and errors.
  Dim mobjPageKey         '::: PageKeys are passed into page as parameters  
  Dim mctlPageStatusLabel '::: Html label generated to display page status.

                          '::: ----- Form Control -----
  Dim mctlForm            '::: Form control.
  Dim mcmdGetForm         '::: ADO Command that retrieves form data.
  Dim mcmdSaveForm        '::: ADO Command that saves form data.
  Dim marecForm           '::: Recordset(s) for the form.
  Dim mobjFormDataBinder  '::: Data binder for the form.

':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
':::  Initialize Page
':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

  '::: Open database connection.
  Set mconConnection = OpenDbConnection

  '::: Authenticate the user who requested the page.
  mintUserID = AuthenticateUser(mconConnection)

  '::: Create and initialize context. It is used to pass user-related
  '::: information and ASP intrinsic objects into the EWAL components.
  Set mobjContext = NewContext(mintUserID)

  '::: Check whether the user is authorized for the page. If not, the
  '::: subroutine will redirect to a page displaying a critical error.
  AuthorizePage mobjContext, mcstrObjectName

  '::: --------------------------
  '::: Resource Dictionary
  '::: --------------------------
  '::: Create resource dictionary to fetch the required labels.
  Set mobjResourceDict = NewObject("ResourceDict", mobjContext)

  '::: We need resources for shared object "Form" and for the page itself.
  mobjResourceDict.AddObjectKey "Form"
  mobjResourceDict.AddObjectKey mcstrObjectName

  '::: Read resources for the given object keys into mobjResourceDict.
  mobjResourceDict.Fill

  '::: --------------------------
  '::: Page Status Object
  '::: --------------------------
  '::: Create PageStatus object. It manages important information about
  '::: the state of the script such as errors and HTTP status.
  Set mobjPageStatus 		= NewObject("PageStatus", mobjContext)
  mobjPageStatus.ObjectName = mcstrObjectName

  '::: Set multilingual text resources for PageStatus.
  mobjPageStatus.InfoText  = mobjResourceDict("StatusTextReady")
  mobjPageStatus.ErrorText = mobjResourceDict("StatusTextError")

':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
'::: Read Parameters
':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

  '::: --------------------------
  '::: Read Page Key(s)
  '::: --------------------------
  mobjPageStatus.PageKeys.Read "{PAGE_KEY}"

  '::: Check page key is a valid record ID and is not null.
  If (Not IsRecordId(mobjPageStatus.PageKeys("{PAGE_KEY}"))) _
    Or IsNull(mobjPageStatus.PageKeys("{PAGE_KEY}")) Then
    '::: Raise critical "bad parameter" error and end script.
    mobjPageStatus.AddAppError gcintErrParameter, "{PAGE_KEY}"
    mobjPageStatus.RaiseCriticalError

  End If

':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
'::: Evaluate Mode
':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

  EvaluateModeSingleForm mobjPageStatus

':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
':::  Create Form
':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

  '::: Prepare stored procedure to fetch data for the form.
  Set mcmdGetForm = CreateSpCommand(mcstrSP_Get, mconConnection)
  mcmdGetForm.Parameters("@vintCurUserID").Value = mobjContext.UserID
  mcmdGetForm.Parameters("@vintCurSysLID").Value = mobjContext.LanguageId
  mcmdGetForm.Parameters("@vint{PAGE_KEY}").Value = mobjPageStatus.PageKeys("{PAGE_KEY}")

  '::: Execute the stored procedure to retrieve data for the form.
  On Error Resume Next
  marecForm = OpenRecordsets(mcmdGetForm)
  If (Err.Number <> 0) Then
    '::: Error trying to fetch data. Append the ADO errors, raise a
    '::: critical "data could not be retrieved" error and end script.
    mobjPageStatus.AddAppError gcintErrDataCouldNotBeRetrieved
    mobjPageStatus.AddAdoErrors mconConnection.Errors
    mobjPageStatus.RaiseCriticalError

  End If
  On Error Goto 0

  '::: Check the record count. Exactly one record is expected.
  If (marecForm(0).RecordCount <> 1) Then
    '::: Raise critical "incorrect number of records" error and end script.
    mobjPageStatus.AddAppError gcintErrDataWrongRecordCount, "1", CStr(marecForm(0).RecordCount)
    mobjPageStatus.RaiseCriticalError

  End If

  '::: Create the form control.
  Set mctlForm = NewObject("FormControl", mobjContext)
  mctlForm.Id = "frm{PAGE_NAME}"

  '::: Create a data binder for the form.
  Set mobjFormDataBinder = NewObject("FormDataBinder", mobjContext)
  Set mobjFormDataBinder.DataSource = marecForm(0)
  Set mobjFormDataBinder.Form = mctlForm
  Set mobjFormDataBinder.PageStatus = mobjPageStatus
  mobjFormDataBinder.Authorization.ObjectName = mcstrObjectName

':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
'::: Create form controls
':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

  '::: Type of object created for bound controls is automatically inferred
  '::: based on the datatype of the database field in the data source.
  {ASP_CREATE_CONTROL}

':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
'::: Call BindFromDataSource to copy values from DataSource to controls.
':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

  '::: If a row security violation is detected when bindng data,
  '::: an error is entered into PageStatus and RaiseCriticalError is called.
  mobjFormDataBinder.BindFromDataSource

':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
'::: Retrieve resource texts for controls, captions and buttons
':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

  AssignFormResources mctlForm, mobjResourceDict

':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
':::  Save Data
':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

  '::: This page is re-entrant. It posts back to itself when the form is
  '::: submitted to save the data to the database.
  ':::
  '::: Note that there is no condition to check mobjPageStatus.HasErrors.
  '::: If a non-critical error has occurred, a BindFromPostBack must still be
  '::: executed so that the values entered by the user are read back into
  '::: the controls so that these values are not lost.
  If (mobjPageStatus.Mode = gcintMode_SubmitEdit) Then

    '::: Read the values entered by the user back into the controls.
    '::: If the structure of the passed data does not match the
    '::: controls on the form or if a row security violation is
    '::: detected, an error is entered into PageStatus.
    mobjFormDataBinder.BindFromPostBack

    '::: If no errors have occurred, then continue saving data.
    If (Not mobjPageStatus.HasErrors) Then
      '::: Prepare stored procedure (ADO command) to save the data.
      Set mcmdSaveForm = CreateSpCommand(mcstrSP_Save, mconConnection)

      '::: Copy values of the form controls and key fields to the ADO
      '::: command parameters. ADO parameters are strongly typed so
      '::: assigning values can cause errors. Error handling is required
      On Error Resume Next
      mcmdSaveForm.Parameters("@vintCurUserID").Value = mobjContext.UserId
      mcmdSaveForm.Parameters("@vintCurSysLID").Value = mobjContext.LanguageId
      mcmdSaveForm.Parameters("@vint{PAGE_KEY}").Value = mobjPageStatus.PageKeys("{PAGE_KEY}")
      {ASP_SAVE_PARAMETER}

      If (Err.Number <> 0) Then
        '::: Raise error that submitted data cannot be passed to the SP.
        mobjPageStatus.AddAppError gcintErrSpParameterAssignment
        '::: Append original VBScript error message for more information.
        mobjPageStatus.AddVbsError Err

      End If
      On Error GoTo 0

    End If

    '::: If no errors have occurred, then continue saving data.
    If (Not mobjPageStatus.HasErrors) Then
      '::: Execute the Save SP, with error handling of course.
      On Error Resume Next
      '::: Syntax: cmd.Execute <RecordsAffected>, <Parameters>, <Options>
      mcmdSaveForm.Execute , ,adExecuteNoRecords
      If (Err.Number <> 0) Then
        '::: Raise error that data could not be saved. Append ADO errors.
        mobjPageStatus.AddAppError gcintErrDataCouldNotBeSaved
        mobjPageStatus.AddAdoErrors mconConnection.Errors

      End If
      On Error Goto 0

    End If

    '::: --------------------------
    '::: Re-Fetch Form Data
    '::: --------------------------

    '::: If no errors have occurred, re-execute Get SP to retrieve the
    '::: data from the database. This will reflect the current state of
    '::: the data, including any changes that may have occurred through
    '::: logic on the back-end.
    If (Not mobjPageStatus.HasErrors) Then

      On Error Resume Next
      marecForm = OpenRecordsets(mcmdGetForm)
      If (Err.Number <> 0) Then
        '::: Error trying to fetch data. Append the ADO errors, raise a
        '::: critical "data could not be retrieved" error and end script.
        mobjPageStatus.AddAppError gcintErrDataCouldNotBeRetrieved
        mobjPageStatus.AddAdoErrors mconConnection.Errors
        mobjPageStatus.RaiseCriticalError

      End If
      On Error Goto 0

      '::: Check the record count. Exactly one record is expected.
      If (marecForm(0).RecordCount <> 1) Then
        '::: Raise critical "incorrect record count" error and end script.
        mobjPageStatus.AddAppError gcintErrDataWrongRecordCount, "1", CStr(marecForm(0).RecordCount)
        mobjPageStatus.RaiseCriticalError

      End If

      '::: Apply newly fetched recordset to the form and copy data values
      '::: from recordset into form controls.
      Set mobjFormDataBinder.DataSource = marecForm(0)

      '::: If a row security violation is detected in BindFromDataSource, an error
      '::: is entered into PageStatus and RaiseCriticalError is called.
      mobjFormDataBinder.BindFromDataSource

    End If '::: Re-fetch form data


    '::: --------------------------
    '::: Raise Events
    '::: --------------------------

    '::: Actions may be configured for this form's events.
    '::: If save was successful, raise the appropiate events
    If (Not mobjPageStatus.HasErrors) Then
      RaiseEvents mcstrObjectName, mobjPageStatus.Mode, mctlForm, mobjContext

    End If

    '::: --------------------------
    '::: Re-Adjust Mode
    '::: --------------------------

    ReadjustModeSingleForm mobjPageStatus, mobjResourceDict

  End If '::: End of Save Data

':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
'::: Configure Form Elements
':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

  '::: Configure which form buttons should be visible.
  mctlForm.SubmitEditButton.Visible    = True
  mctlForm.SubmitCancelButton.Visible  = True

':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
'::: Create Page Status Label
':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

  '::: Create a label to display the page status.
  Set mctlPageStatusLabel = mobjPageStatus.CreateStatusLabel

':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
':::  Dispose objects
':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

  '::: Tidy up and free resources. Some object references here may not
  '::: be valid but an error in this tidy up block can be ignored.
  On Error Resume Next

  '::: -----  Form Objects -----
  Set mcmdGetForm = Nothing
  Set mcmdSaveForm = Nothing
  Set mobjFormDataBinder = Nothing
  marecForm(0).Close
  Set marecForm(0) = Nothing

  On Error Goto 0

':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
':::  Render the Interface
':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
%>
<html>
<head>
  <link rel="stylesheet" href="<%= mobjContext.ApplicationRootPath & mobjResourceDict("CssPath") %>">
  <script type="text/javascript" src="<%= mobjContext.ApplicationRootPath %>/system/ClientScript/ScrollScript.asp"></script>
  <title><% mobjResourceDict.RenderText "FormTitle" %></title>
</head>
<body>
<!-- -----------------------------------------------
     Page Header
------------------------------------------------ -->
<div id="PageHeader" class="PageHeader">
  <%
  '::: Display Banner.
  RenderBanner mobjContext, mconConnection
  %>
  <div class="EmployeeFormTitle" >
    <% mobjResourceDict.RenderText "FormTitle" %>
  </div>
</div>

<!-- -----------------------------------------------
     Page Body (scrolling)
------------------------------------------------ -->
<div id="PageBody" class="PageBodyForm">
  <%
  '::: Render the opening <form> tag.
  mctlForm.BeginRender

  For Each mobjPageKey in mobjPageStatus.PageKeys
    mctlForm.GetControl(mobjPageKey.Name).Render
  Next
  %>  
  <table class="FormLayoutTable">
    <colgroup>
      <col style="width:25%"></col>
      <col style="width:25%"></col>
      <col style="width:25%"></col>
      <col style="width:25%"></col>
    </colgroup>
    {ASP_RENDER_LAYOUT}
    <tr>
      <td colspan="4">&nbsp;</td>
    </tr>
    <tr>
      <td colspan="4" style="text-align:right;"><% mctlForm.RenderButtons %></td>
    </tr>

  </table>
  <%
  '::: Render the closing <form> tag
  mctlForm.EndRender
  %>
</div>
<!-- -----------------------------------------------
     Page Footer
------------------------------------------------ -->
<div id="PageFooter" class="PageFooter">
  <%
  '::: Display page status label.
  mctlPageStatusLabel.Render

  '::: Render object help.
  RenderObjectHelp mcstrObjectName, _
                   mobjContext, _
                   mconConnection

  %>
</div>
</body>
</html>
